import DBTools from './simpleWebSql.js'
// import DBTools from './SmpWebSql.js'


class DAL{
	constructor(){
		this.init();
	};

	init(){
		this.db = new DBTools();
	};

	to(promise) {
		return promise.then(data => {
				return [null, data];
			})
			.catch(err => [err]); // es6的返回写法
	};

	async SelectDataFieldArrayFromDB(tableName,field,condition){
		let persionIDArray = new Array();
		let rowArray = await this.db.readField(tableName,field,condition);

		if(rowArray==undefined){
			console.error("发生了数据库读写异常");
			return persionIDArray
		}
		rowArray.forEach(function(item){

			if(!item[0]){
				persionIDArray.push(item[1])
			}
			else{////这里是数据库报错，如何利用起来？
				console.log(item[0]);
				console.log(item[1]);
			}

		});

		return persionIDArray;
	}


	async SelectDataFieldArrayFromDBByCmd(sqlString){
		let persionIDArray = new Array();
		console.log(sqlString)
		let rowArray = await this.db.readFieldByCommand(sqlString);

		if(rowArray==undefined){
			console.error("发生了数据库读写异常");
			return persionIDArray
		}
		rowArray.forEach(function(item){

			if(!item[0]){
				persionIDArray.push(item[1])
			}
			else{////这里是数据库报错，如何利用起来？
				console.log(item[0]);
				console.log(item[1]);
			}

		});

		return persionIDArray;
	}


	//返回的是数组，数组里面是json
	async SelectDataArrayFromDB(tableName,condition){
		let persionIDArray = new Array();
		let rowArray = await this.db.read(tableName,condition).catch(error=>{});

		if(rowArray==undefined){
			console.error("发生了数据库读写异常");
			return persionIDArray
		}

		rowArray.forEach(function(item){
			if(!item[0]){
				persionIDArray.push(item[1])
			}
			else{//这里是数据库报错，如何利用起来？
				console.log(item[0]);
				console.log(item[1]);
			}

		});

		return persionIDArray;
	}

	async androidCounts(tableName,condition){
		let temp = await this.SelectDataFieldArrayFromDB(tableName,'count(DISTINCT A0000) as num',condition);
		return temp[0].num;
	}

	async deleteDate(){
		let DBName = ['a01','a02','a05','a06','a08','a14','a15','a36','a99z1','b01'];
		for(let i=0;i<DBName.length;i++){
			let deleteString = `DELETE FROM "${DBName[i]}"`;
			let rowArray = await this.db.readFieldByCommand(deleteString);
			console.log(rowArray)
		}
	}
}


export default DAL;
